import React from 'react';
import { connect } from 'dva';
import { Form, Input, Button } from 'antd';
import Message from '../Message/Message';
import styles from './Chatroom.css';

const FormItem = Form.Item;
class ChatroomForm extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      msg: [],
      news: null,
    };
  }

  componentWillReceiveProps(nextProp) {
    this.setState({ msg: nextProp.chat.msg });
  }

  componentDidUpdate() {
    const content = this.refs.myCon;
    content.scrollTop = content.scrollHeight;
  }

  componentWillUnmount() {
    const userName = this.props.ready.data.username;
    const roomNum = this.props.ready.data.roomnum;
    this.props.dispatch({
      type: 'chat/leave',
      payload: { userName, roomNum },
    });
  }

  handleSubmit = (e) => {
    e.preventDefault();
    const roomnum = this.props.ready.data.roomnum;
    const speaker = this.props.ready.data.username;
    const news = this.state.news;
    this.props.dispatch({
      type: 'chat/submit',
      payload: { roomnum, speaker, news },
    });
    this.appendUser(speaker, news);
    this.refs.roomnum.input.value = '';
  }

  appendUser = (speaker, news) => {
    const date = new Date();
    const hour = date.getHours();
    const miute = date.getMinutes();
    const second = date.getSeconds();
    const usermsg = { speaker, news, date: `${hour}:${miute}:${second}` };
    this.props.dispatch({
      type: 'chat/userMsg',
      payload: usermsg,
    });
  }

  handleNews=(e) => {
    const news = e.target.value;
    this.setState({ news });
  }
  render() {
    return (
      <div className={styles.chatroom}>
        <div className={styles.title}>
          <h3>聊天室</h3>
        </div>
        <div className={styles.content} ref="myCon">
          <div>打声招呼吧！</div>
          {
            this.state.msg.map((main, i) => {
              main.username = this.props.ready.data.username;
              return (<Message key={i}>{main}</Message>);
            })
          }
        </div>
        <div className={styles.send}>
          <Form layout="inline" onSubmit={this.handleSubmit}>
            <FormItem >
              {
                <Input
                  type="text"
                  placeholder="回车键发送"
                  onChange={this.handleNews}
                  ref="roomnum"
                />
              }
            </FormItem>
            <FormItem>
              <Button
                type="primary"
                htmlType="submit"
              >
                发送
              </Button>
            </FormItem>
          </Form>
        </div>
      </div>
    );
  }

}

const Chatroom = Form.create()(ChatroomForm);
function mapStateToProps(state) {
  const ready = state.ready;
  const chat = state.chat;
  return { ready, chat };
}
export default connect(mapStateToProps)(Chatroom);
